package com.bicon.botu.mall.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.order.common.OrderConstans;
import com.bicon.botu.mall.order.common.OrderUtil;
import com.bicon.botu.mall.order.dto.AllOrderDto;
import com.bicon.botu.mall.order.dto.OrderDto;
import com.bicon.botu.mall.order.entity.GoodsOrder;
import com.bicon.botu.mall.order.entity.OrderAddress;
import com.bicon.botu.mall.order.entity.OrderItem;
import com.bicon.botu.mall.order.mapper.GoodsOrderMapper;
import com.bicon.botu.mall.order.mapper.OrderAddressMapper;
import com.bicon.botu.mall.order.service.IGoodsOrderService;
import com.bicon.botu.mall.order.service.IOrderItemService;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务实现层
 *
 * @auther 裴志鹏
 * @date 2017/7/20 10:37
 */
@Slf4j
@Service
@Transactional
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements IGoodsOrderService {

    @Autowired
    private IOrderItemService iOrderItemService;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    /**
     * 提交订单
     *
     * @param userId                   用户id
     * @param orderAmount              订单总金额
     * @param sourceCode               订单来源
     * @param promotionsDiscountIdJson 优惠券id集合
     * @param expressAmount            邮费
     * @param remark                   买家留言
     * @param goodsIdJson              商品id集合  多个商品使用,号分隔
     * @param goodsNameJson            商品名称
     * @param goodsNumberJson          商品数量集合
     * @param skuNameJson              sku名称集合
     * @param itemImageJson            商品列表展示图集合
     * @param goodsPlatformPriceJson   商品价格集合
     * @param name                     收货人
     * @param address                  收货地址
     * @param telephone                联系电话
     * @param flag                     是否从购物车提交订单 0-是 1-否
     * @param goodsFrom                1 商品  2 食物
     * @return
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public BaseResult submitOrder(String userId, String orderAmount, String sourceCode, String promotionsDiscountIdJson, String expressAmount, String remark, String goodsIdJson, String goodsNameJson,
                                  String goodsNumberJson, String skuNameJson, String itemImageJson, String goodsPlatformPriceJson, String name, String address, String telephone, String flag,String goodsFrom) {
//      校验商品是否下架
        List<String> goodIdList = JSONObject.parseArray(goodsIdJson,String.class);
        List<String> goodsNumberList = JSONObject.parseArray(goodsNumberJson, String.class);
        List<String> goodsNameList = JSONObject.parseArray(goodsNameJson, String.class);
        Map<String, Object> map = new HashMap<>();
        if("1".equals(goodsFrom)){
            map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
            String result = "";
            for (int i = 0; i < goodIdList.size(); i++) {
                map.put("goodsId", goodIdList.get(i));
                String upShelves = goodsOrderMapper.findProductUpShelves(map);
                if ("1".equals(upShelves)) {//下架
                    result += goodIdList.get(i) + ",";
                }
            }
            if (StringUtils.isNotBlank(result)) {
                return new BaseResult(606, "", parameterDistinct(result));
            }
//      校验商品库存
            String data = "";
            for (int i = 0; i < goodIdList.size(); i++) {
                map.put("goodsId", goodIdList.get(i));
                String productNum = goodsOrderMapper.findRepertory(map);
                if (StringUtils.isEmpty(productNum)) {
                    data += goodIdList.get(i) + ",";
                } else if (new BigDecimal(productNum).subtract(new BigDecimal(goodsNumberList.get(i))).intValue() < 0) {
                    data += goodIdList.get(i) + ",";
                }
            }
            if (StringUtils.isNotBlank(data)) {
                return new BaseResult(Constants.RESPONSE_CODE_602, "", parameterDistinct(data));
            }
        }


//      生成一个订单
//      随机生成一个订单号
        String orderNo = OrderUtil.getOrderNo();
        GoodsOrder order = new GoodsOrder();
        order.preInsert();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setStatus(OrderConstans.ORDER_STATUS_01);
        order.setOrderAmount(new BigDecimal(orderAmount));
        order.setSourceCode(Integer.parseInt(sourceCode));
//        order.setPromotionsDiscountId(promotionsDiscountId);
        order.setExpressAmount(new BigDecimal(expressAmount));
        order.setRemark(remark);
        boolean b = order.insert();
//      保存订单地址
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.preInsert();
        orderAddress.setOrderId(order.getId());
        orderAddress.setUserId(userId);
        orderAddress.setName(name);
        orderAddress.setAddress(address);
        orderAddress.setTelephone(telephone);
        boolean b1 = orderAddress.insert();
        if (b && b1) {
//      保存订单子项
            ArrayList<String> skuNameList = JsonUtil.fromJson(skuNameJson, ArrayList.class);
            ArrayList<String> itemImageList = JsonUtil.fromJson(itemImageJson, ArrayList.class);
            ArrayList<String> goodsPlatformList = JsonUtil.fromJson(goodsPlatformPriceJson, ArrayList.class);
            ArrayList<String> promotionsDiscountIdList = JsonUtil.fromJson(promotionsDiscountIdJson, ArrayList.class);
            List<OrderItem> orderItemList = new ArrayList<>();
            for (int i = 0; i < goodIdList.size(); i++) {
                OrderItem orderItem = new OrderItem();
                orderItem.preInsert();
                orderItem.setOrderId(order.getId());
                orderItem.setGoodsId(goodIdList.get(i));
                orderItem.setGoodsName(goodsNameList.get(i));
                orderItem.setGoodsNumber(Integer.parseInt(goodsNumberList.get(i)));
                orderItem.setSkuName(skuNameList.get(i));
                orderItem.setItemImage(itemImageList.get(i));
                orderItem.setGoodsPlatformPrice(new BigDecimal(goodsPlatformList.get(i)));
                orderItem.setPromotionsDiscountId(promotionsDiscountIdList.get(i));
                orderItemList.add(orderItem);
//              修改商品的库存及销量
                if ("1".equals(goodsFrom)){
                    map.put("goodsId", goodIdList.get(i));
                    map.put("goodsNumber", Integer.parseInt(goodsNumberList.get(i)));
                    goodsOrderMapper.updateRepertory(map);
                }
            }
            boolean batchInsertFlag = iOrderItemService.insertBatch(orderItemList);
            if (!batchInsertFlag){
                throw new BusinessException(Constants.RESPONSE_CODE_500,Constants.RESPONSE_MESSAGE_500);
            }
            if("1".equals(goodsFrom)){
                map.clear();
//          校验是否从购物车提交的订单
                if (StringUtils.isNotEmpty(flag) && "0".equals(flag)) {
                    map.put("userId", userId);
                    for (String s : goodIdList) {
                        map.put("goodId", s);
                        goodsOrderMapper.deleteCart(map);
                    }
                }
            }

            if (StringUtils.isNotEmpty(promotionsDiscountIdJson)) {
//              修改优惠券使用状态
                Map<String, Object> couponsMap = new HashMap();
                couponsMap.put("userId", userId);
                couponsMap.put("list", promotionsDiscountIdList);
                couponsMap.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
                goodsOrderMapper.updateCoupons(couponsMap);
            }
        } else {
            throw new BusinessException(Constants.RESPONSE_CODE_500,Constants.RESPONSE_MESSAGE_500);
//            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200,order.getId());
    }


    private String parameterDistinct(String data) {
        String[] str = data.split(",");
        List<String> list = new ArrayList();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            if (!list.contains(str[i])) {
                list.add(str[i]);
                sb.append(str[i] + ",");
            }
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    /**
     * 修改订单接口
     *
     * @param orderId      订单id
     * @param actualAmount 实际支付金额
     * @param name         收货人
     * @param address      收货地址
     * @param telephone    联系电话
     * @return
     */
    @Override
    public BaseResult update(String orderId, String actualAmount, String name, String address, String telephone) {
        if (StringUtils.isNotEmpty(actualAmount)) {
            GoodsOrder goodsOrder = new GoodsOrder();
            goodsOrder.preUpdate();
            goodsOrder.setId(orderId);
            goodsOrder.setActualAmount(new BigDecimal(actualAmount));
            goodsOrder.updateById();
        }
        if (StringUtils.isNotEmpty(name)) {
            OrderAddress orderAddress = new OrderAddress();
            orderAddress.setOrderId(orderId);
            orderAddress.setName(name);
            orderAddress.setAddress(address);
            orderAddress.setTelephone(telephone);
            orderAddressMapper.updateOrderAddress(orderAddress);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 无效
     *
     * @param goodsOrderId 订单id
     * @return
     */
    @Override
    public BaseResult updateByOrderId(String goodsOrderId) {
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.preUpdate();
        goodsOrder.setId(goodsOrderId);
        goodsOrder.setStatus(OrderConstans.ORDER_STATUS_06);
        goodsOrder.setCancelReason("后台取消");
        boolean b = goodsOrder.updateById();
        if (b) {
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 分页查询订单列表
     *
     * @param pageNo   页码
     * @param pageSize 每页显示数量
     * @return
     */
    @Override
    public Page<OrderDto> findOrderList(int pageNo, int pageSize) {
        Page<OrderDto> page = new Page<>(pageNo, pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        List<OrderDto> orderDtoList = goodsOrderMapper.findOrderList(page, map);
        page.setRecords(orderDtoList);
        return page;
    }

    /**
     * 按类型查询订单列表
     *
     * @param pageNo   页码
     * @param pageSize 每页显示数量
     * @param type     发货、退货、退换货类型
     * @return
     */
    @Override
    public Page<OrderDto> findOrderByPayment(int pageNo, int pageSize, String type) {
        Page<OrderDto> page = new Page<>(pageNo, pageSize);
        Map<String, String> map = new HashMap<>();
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("orderStatus", type);
        List<OrderDto> orderDtoList = goodsOrderMapper.findOrderList(page, map);
        page.setRecords(orderDtoList);
        return page;
    }

    /**
     * 取消订单
     *
     * @param orderId      订单id
     * @param userId       用户id
     * @param cancelReason 取消订单原因
     * @return
     */
    @Override
    public BaseResult cancelOrder(String orderId, String userId, String cancelReason) {
//      修改订单状态
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.preUpdate();
        goodsOrder.setId(orderId);
        goodsOrder.setUserId(userId);
        goodsOrder.setStatus(OrderConstans.ORDER_STATUS_06);
        goodsOrder.setCancelReason(cancelReason);
        boolean b = goodsOrder.updateById();
        if (b) {
//      修改商品库存
            List<OrderItem> orderItemList = new OrderItem().selectList(new EntityWrapper<OrderItem>().eq("order_id", orderId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            Map<String, Object> map = new HashMap<>();
            map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
            for (OrderItem o : orderItemList) {
                map.put("goodsId", o.getGoodsId());
                map.put("goodsNumber", o.getGoodsNumber());
                goodsOrderMapper.recoverRepertory(map);
            }
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 删除订单
     *
     * @param orderId 订单id
     * @param userId  用户id
     * @return
     */
    @Override
    public BaseResult deleteOrder(String orderId, String userId) {
//      删除订单
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setLogicDelete(Constants.DEL_LOGIC_DELETE);
        boolean b = goodsOrder.update(new EntityWrapper<GoodsOrder>().eq("id", orderId).eq("user_id", userId));
        if (b) {
//          删除订单子项表数据
            OrderItem orderItem = new OrderItem();
            orderItem.setLogicDelete(Constants.DEL_LOGIC_DELETE);
            orderItem.update(new EntityWrapper<OrderItem>().eq("order_id", orderId));
            return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
        } else {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
    }

    /**
     * 我的订单-待付款、代发货、待收货、待评价
     *
     * @param userId  用户id
     * @param status  订单状态
     * @param current 当前页
     * @param size    每页条数
     * @return
     */
    @Override
    public BaseResult myOrder(String userId, String status, int current, int size) {
        Page<AllOrderDto> page = new Page<>(current, size);
        Map<String, Object> map = new HashMap<>(3);
        map.put("userId", userId);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        if (StringUtils.isNotEmpty(status)) {
            map.put("status", status);
        }
        List<AllOrderDto> allOrderDtoList = goodsOrderMapper.findAllOrder(page, map);
        for (AllOrderDto a : allOrderDtoList) {
            List<OrderItem> orderItemList = new OrderItem().selectList(new EntityWrapper<OrderItem>().eq("order_id", a.getOrderId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            Integer goodsNum=0;
            for (OrderItem orderItem:orderItemList){
                goodsNum=goodsNum+ orderItem.getGoodsNumber();
            }
            a.setOrderNum(goodsNum);
            a.setOrderItems(orderItemList);
        }
        page.setRecords(allOrderDtoList);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, page);
    }

    /**
     *  用户下的订单详情信息
     * @param userId 用户Id
     * @param orderId 订单id
     * @return
     */
    @Override
    public BaseResult getOrderDetails(String userId,  String orderId){
        Page<AllOrderDto> page = new Page<>();
        Map<String, Object> map = new HashMap<>(3);
        map.put("userId", userId);
        map.put("orderId", orderId);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        List<AllOrderDto> allOrderDtoList = goodsOrderMapper.findAllOrder(page,map);
        for (AllOrderDto a : allOrderDtoList) {
            List<OrderItem> orderItemList = new OrderItem().selectList(new EntityWrapper<OrderItem>().eq("order_id", a.getOrderId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            OrderAddress orderAddress = new OrderAddress().selectOne(new EntityWrapper<OrderAddress>().eq("user_id",userId).eq("order_id", a.getOrderId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            Integer goodsNum=0;
            for (OrderItem orderItem:orderItemList){
                goodsNum=goodsNum+ orderItem.getGoodsNumber();
            }
            a.setOrderNum(goodsNum);
            a.setOrderAddress(orderAddress);
            a.setOrderItems(orderItemList);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, allOrderDtoList);
    }


    /**
     *  根据商品名称搜索订单
     * @param userId 用户Id
     * @param words 订单id
     * @return
     */
    @Override
    public BaseResult queryOrderByGoodsName(String userId,String words){
        Map<String, Object> map = new HashMap<>(3);
        map.put("userId", userId);
        map.put("logicDelete", Constants.DEL_LOGIC_NORMAL);
        map.put("remark", words);//用备注代替搜索词
        List<AllOrderDto> allOrderDtoList = goodsOrderMapper.queryOrderByGoodsName(map);
        for (AllOrderDto a : allOrderDtoList) {
            List<OrderItem> orderItemList = new OrderItem().selectList(new EntityWrapper<OrderItem>().eq("order_id", a.getOrderId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
//            OrderAddress orderAddress = new OrderAddress().selectOne(new EntityWrapper<OrderAddress>().eq("user_id",userId).eq("order_id", a.getOrderId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            Integer goodsNum=0;
            for (OrderItem orderItem:orderItemList){
                goodsNum=goodsNum+ orderItem.getGoodsNumber();
            }
            a.setOrderNum(goodsNum);
//            a.setOrderAddress(orderAddress);
            a.setOrderItems(orderItemList);
        }
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, allOrderDtoList);
    }
}
